<?php
/**
 * Author: 孙武 QQ:1228746736
 * Date: 2018/2/16
 * Time: 18:45
 */

namespace app\home\def;

use PHPMailer\PHPMailer\PHPMailer;
use think\captcha\Captcha;
use think\Db;

class Helper
{
    /**
     * 发送邮件
     * @param $to
     * @param $title
     * @param $body
     * @return array
     */
    public static function sendMail($to, $title, $body)
    {
        $mail = new PHPMailer;
        $mail->isSMTP();
//        $mail->SMTPDebug = 2
        $mail->Host = 'smtp.qq.com';
        $mail->SMTPAuth = true;
        $mail->Username = '1228746736@qq.com';
        $mail->Password = 'swylarbricgbijde';
        $mail->SMTPSecure = 'tls';
        $mail->Port = 587;
        $mail->setFrom('1228746736@qq.com', '孙武');
        $mail->addAddress($to);
        $mail->isHTML(true);
        $mail->Subject = $title;
        $mail->Body = $body;
        if (!$mail->send()) {
            return [
                'errno' => -1,
                'errmsg' => $mail->ErrorInfo
            ];
        } else {
            return [
                'errno' => 0,
                'errmsg' => $mail->ErrorInfo
            ];
        }
    }

    /**
     * 检验验证码
     * @param $code
     * @param string $id
     * @return bool
     */
    public static function checkVercode($code, $id = '')
    {
        $option = ['reset' => false];
        $captcha = new Captcha($option);
        if ($captcha->check($code, $id)) {
            return true;
        }
        return false;
    }


    /**
     * 权限验证
     * @param $uid
     * @param $allowUid
     * @return bool
     */
    public static function checkAuth($uid,$allowUid)
    {
        if(in_array($uid,$allowUid)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 解析资源信息
     * 解析联合查询而来的数据并过滤
     * 包含的表
     * 1 资源表
     * 2 用户表
     * 3 分类表
     * 4 评论表
     * @param $data
     * @return array
     *
     */
    public static function parseResData($data)
    {
        $returnArr=[];
        if(is_array($data) && !empty($data)){
            foreach ($data as $resData){
                $t=[
                    'resguid' => $resData['PK_ResourceGuid'], //资源的guid
                    'userguid' => $resData['FK_UserGuid'],//用户的guid
                    'name' => $resData['user']['Name'],//资源拥有者姓名
                    'level' => $resData['user']['Level'],//用户等级
                    'cover' => $resData['user']['Cover'],//用户头像
                    'title' => $resData['Title'],//资源名称
                    'catname' => $resData['category']['Name'],//资源所属分类名称
                    'createTime' => $resData['CreateTime'],//资源创建时间`
                    'price' => $resData['Price'],//资源价格
                    'downloads' => $resData['Downloads'],//下载量,
                    'comments' => count($resData['rescomment'])//评论量
                ];
                $returnArr[]=$t;
            }
        }
        return $returnArr;
    }

    public static function mysqlBackup($backFile)
    {
        $backDirectory = ROOT_PATH . 'runtime' . DS . 'backup';
        $realBackDirectory = $backDirectory . '/' . $backFile;
        if (!file_exists($backDirectory)) {
            $result = mkdir($backDirectory, 0777, true);
            if (!$result) {
                exception('runtime目录没有读写权限！', 1002);
            }
        }
        $dbName = 'Tables_in_' . config('database')['database'];
        if (!$dbName) {
            exception('数据库名称没有配置，请检查配置', 1001);
        }
        $tableName = Db::query('show tables');
        if (!$tableName) {
            exception('数据库中没有表，无法备份！', 1004);
        }
        $fp = fopen($realBackDirectory, 'w') or exception('追加方式打开文件失败，请重新备份！', 1003);
        fwrite($fp, "/*\n *梦中PHP系列教程提供\n *QQ:305530751\n*/\n\n");
        foreach ($tableName as $k => $v) {
            $info = "DROP TABLE IF EXISTS `{$v[$dbName]}`;\n";
            $data = Db::query("show create table {$v[$dbName]}");
            $info .= $data[0]['Create Table'];
            fwrite($fp, $info . ";\n\n");

            $insertData = Db::name($v[$dbName])->select();
            foreach ($insertData as $k1 => $v1) {
                $insertSql = "INSERT INTO {$v[$dbName]} VALUES(";
                foreach ($v1 as $k2 => $v2) {
                    $insertSql .= "'" . $v2 . "',";
                }
                $insertSql = trim($insertSql, ',') . ');';
                fwrite($fp, $insertSql . "\n");
            }
        }
        fclose($fp);
        return ['errno' => 0, 'errmsg' => '备份完成！'];
    }

}